# app/config.py
from typing import List, Optional
from pydantic import BaseSettings, validator
import multiprocessing


class Settings(BaseSettings):
    # 基本配置
    APP_NAME: str = "FastAPI App"
    DEBUG: bool = True
    API_STR: str = "/api"

    # 数据库配置
    DB_HOST: str = "localhost"
    DB_PORT: int = 3306
    DB_USER: str = "root"
    DB_PASSWORD: str = "123456"
    DB_NAME: str = "jiayi"

    # 计算建议的连接池大小
    CPU_COUNT: int = multiprocessing.cpu_count()
    DB_MIN_SIZE: int = 1
    DB_MAX_SIZE: int = (CPU_COUNT * 2) + 1  # 推荐配置
    DB_CONNECT_TIMEOUT: int = 60  # 连接超时时间（秒）

    @property
    def DATABASE_URL(self) -> str:
        return f"mysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"

    # Tortoise ORM配置
    @property
    def TORTOISE_ORM(self) -> dict:
        return {
            "connections": {
                "default": {
                    "engine": "tortoise.backends.mysql",
                    "credentials": {
                        "host": self.DB_HOST,
                        "port": self.DB_PORT,
                        "user": self.DB_USER,
                        "password": self.DB_PASSWORD,
                        "database": self.DB_NAME,
                        "minsize": self.DB_MIN_SIZE,
                        "maxsize": self.DB_MAX_SIZE,
                        "connect_timeout": self.DB_CONNECT_TIMEOUT,
                        "pool_recycle": 3600,  # 连接回收时间（秒）
                    }
                }
            },
            "apps": {
                "model": {
                    "models": ["model"],  # 模型所在的路径
                    "default_connection": "default",
                }
            },
            "use_tz": False,
            "timezone": "Asia/Shanghai",

            # 连接配置
            "connect_retries": 3,  # 连接重试次数
            "retry_delay": 1,  # 重试延迟（秒）

            # 事务隔离级别
            "isolation_level": "read_committed"  # 或 "repeatable_read"
        }

    # 安全配置
    SECRET_KEY: str = "your-super-secret-key"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24  # 24 小时
    ALLOWED_HOSTS: List[str] = ["*"]

    # CORS配置
    CORS_ORIGINS: List[str] = ["*"]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["*"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]

    # 缓存配置
    REDIS_HOST: Optional[str] = None
    REDIS_PORT: int = 6379
    REDIS_DB: int = 0
    REDIS_PASSWORD: Optional[str] = 123456

    @property
    def REDIS_URL(self) -> Optional[str]:
        if self.REDIS_HOST:
            auth = f":{self.REDIS_PASSWORD}@" if self.REDIS_PASSWORD else "@"
            return f"redis://{auth}{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
        return None

    # 日志配置
    LOG_LEVEL: str = "DEBUG" if DEBUG else "INFO"
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

    # 文件上传配置
    UPLOAD_DIR: str = "uploads"
    MAX_UPLOAD_SIZE: int = 1024 * 1024 * 5  # 5MB

    # 性能优化配置
    PAGINATION_PAGE_SIZE: int = 10
    MAX_PAGINATION_PAGE_SIZE: int = 100

    class Config:
        case_sensitive = True
        env_file = ".env"  # 支持从.env文件加载配置


# 创建配置实例
settings = Settings()

# 示例 .env 文件内容
"""
# .env
APP_NAME=My FastAPI App
DEBUG=True
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=123456
DB_NAME=blog
SECRET_KEY=your-super-secret-key
"""